<?php

namespace app\admin\controller;
use app\common\model\News as NewsModel;
use app\common\model\Newscat as CateModel;
use think\Controller;
use think\Request;

class Newscat extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $cate=new CateModel();
        if(request()->isPost()){
            $sorts=input('post.');
            foreach ($sorts as $k => $v) {
                $cate->update(['catid'=>$k,'displayorder'=>$v]);
            }
            return $this->success('更新排序成功！',url('index'));

        }
        $category=model('Newscat')->catetree();

        return $this->fetch('',['category'=>$category]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $category=model('Newscat')->catetree();
        return $this->fetch('add',['category'=>$category]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        if(request()->isPost()) {

            $data = input('post.');
            $catid=model('Newscat')->create($data, true);;
            if($catid)
            {
                return $this->success('新增成功','index');
            }else{
                return $this->success('新增失败','index');
            }



        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $cate =model('Newscat')::find($id);
        $catelist=model('Newscat')->catetree();


        return $this->fetch('edit',['cate'=>$cate,
            'catelist'=>$catelist
        ]);

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $data = input('post.');

        model('Newscat')::update($data,['catid' => $data['catid']], true);


        $this->success('修改成功', 'index');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function del($id)
    {
        $news=model('News')->where(['catid'=>$id])->select();
        if($news)
        {
            return json(['code' => '0', 'msg' => '删除失败，请先删除该分类下的新闻']);
        }

        CateModel::destroy($id);

        return json(['code' => '200', 'msg' => '操作成功']);
    }

    public function delsoncate(){
        $id=input('id');
        $cate=new CateModel();
        $sonids=$cate->getchilrenid($id);
        if($sonids){
            db('Category')->delete($sonids);
        }
    }

}
